package com.leff.cards.request;

import com.leff.cards.Dictionary;
import com.leff.cards.StoreWrapper;
import com.leff.cards.entity.User;

public class GCMRegister extends Request {

	public GCMRegister(Dictionary dict) {
		super(dict);
	}
	
	public RequestResult doRegister() {
		
		RequestResult res = this.verifyRequiredParameters(Parameter.ID, Parameter.GCM_ID);
		if(!res.isSuccessful()) {
			return res;
		}

		String idStr = (String)mDictionary.get(Parameter.ID);
		long id = Long.parseLong(idStr);

		// Find the user
		User U = StoreWrapper.getUserById(id);
		if(U == null) {
			res.setErrorResult("No user with id " + idStr + " found in datastore");
			return res;
		}
		
		String gcmId = (String)mDictionary.get(Parameter.GCM_ID);
		U.addDeviceId(gcmId);
		StoreWrapper.store(U);
		
		res.setSuccessMessage("Device token " + gcmId + " registered to user " + id);
		
		return res;
	}
	
	public RequestResult doUnregister() {
		
		RequestResult res = this.verifyRequiredParameters(Parameter.ID, Parameter.GCM_ID);
		if(!res.isSuccessful()) {
			return res;
		}

		String idStr = (String)mDictionary.get(Parameter.ID);
		long id = Long.parseLong(idStr);

		// Find the user
		User U = StoreWrapper.getUserById(id);
		if(U == null) {
			res.setErrorResult("No user with id " + idStr + " found in datastore");
			return res;
		}
		
		String gcmId = (String)mDictionary.get(Parameter.GCM_ID);
		U.removeDeviceId(gcmId);
		StoreWrapper.store(U);
		
		res.setSuccessMessage("Device token " + gcmId + " unregistered from user " + id);
		
		return res;
	}
}
